package controllers

import (
	"findme-api/models"
	"github.com/astaxie/beego"
	"fmt"
	"path"
	"github.com/astaxie/beego/orm"
	"strings"
	"time"
)


//文件相关接口
type FileController struct {
	beego.Controller
}



type File struct {
	Id string `json:"id"`
	Filename string `json:"filename"`
	Filetype string `json:"filetype"`
	Deviceid string `json:"deviceid"`
	Company  string  `json:"company"`
	Uploadtime string `json:"uploadtime"`
}

type FILEJSONS struct {
	//必须的大写开头
	Error_code int `json:"error_code"`
	Total int `json:"total"`
	DATA []File  `json:"data"`
}




//上传下载文件的页面
func (c * FileController) Get() {
	c.TplName = "upload.html"
}


//上传文件
func (this *FileController) Fileupload() {
	FileLogs.Info("====上传文件====")
	file, information, err := this.GetFile("file")  //返回文件，文件信息头，错误信息
    filetype := this.GetString("filetype")
	deviceid := this.GetString("deviceid")


	//查询该设备所属公司
	var labelrows []models.LabelInfo
	o := orm.NewOrm()
	if _, err := o.Raw("SELECT * FROM label_info  where labelid = ?",deviceid ).QueryRows(&labelrows); err != nil{
		FileLogs.Info("error")
		return
	}
	var company = ""
	for _,labelrow := range labelrows{
		company = labelrow.Unit
		break
	}

	if err != nil {
		this.Ctx.WriteString("File retrieval failure")
		return
	}
	defer file.Close()    //关闭上传的文件，否则出现临时文件不清除的情况  mmp错了好多次啊

	timeUnix:=time.Now().Unix()
	timeStr:=time.Now().Format("2006-01-02 15:04:05")

	filename := information.Filename           //将文件信息头的信息赋值给filename变量
	err = this.SaveToFile("file", path.Join("static/upload",filename))  //保存文件的路径。保存在static/upload中   （文件名）
	Filedata := models.FileInfo{Filename:filename,Filetype:filetype,Filepath:"static/upload",Deviceid:deviceid,Company:company,Timestamp:timeUnix,Uploadtime:timeStr}
	_,err1:= models.AddFile(&Filedata)

	type JSONS struct {
		//必须的大写开头
		Error_code int
	}

	if (err != nil)&&(err1 != nil) {
		data := &JSONS{1,}
		this.Data["json"] = data
		this.ServeJSON()
	} else {
		data := &JSONS{0}
		this.Data["json"] = data
		this.ServeJSON()
	}
	//this.TplName = "upload.html"             //停留在当前界面
}



//文件下载方法
func (this *FileController) FileDownload() {
	filename := this.GetString("filename")
	fmt.Println("filename", filename)
	//第一个参数是文件的地址，第二个参数是下载显示的文件的名称
	this.Ctx.Output.Download("static/upload/1575452219759.3gp")
}


//查询所有文件
func (this *FileController) QueryAllFileInfo() {
	token := this.Ctx.Request.Header.Get("token")
	company := GetCompanyfromToken(token)
    page := this.GetString("page")
    size := this.GetString("size")

	fileDataChan := make(chan string, 100000)
	totalItem := models.ReadFile(fileDataChan,company,page,size)
	filedata := []File{}
	tempdata := File{"null","null","null","null","null","null"}
	//遍历信道，读取数据
	var i int = 0
	var lenfiledatachan = len(fileDataChan)
	if lenfiledatachan != 0 {
		for item := range fileDataChan{
			itemsegments := strings.Split(item,"and")
			tempdata = File{itemsegments[0],itemsegments[1],itemsegments[2],itemsegments[3],itemsegments[4],itemsegments[5]}
			filedata = append(filedata, tempdata)
			if i == (lenfiledatachan - 1) {
				break
			}
			i++
		}
		data := &FILEJSONS{0,totalItem,filedata}
		this.Data["json"] = data
		this.ServeJSON()
	}else {
		filedata = append(filedata, tempdata)
		data := &FILEJSONS{1, 0, []File{}}
		this.Data["json"] = data
		this.ServeJSON()
	}
}










